
import 'dart:convert';
import 'dart:io';

import 'package:logger/logger.dart';
import 'dart:developer';

import 'package:realmega_ota/realmega/running_log_manager.dart';

/// Writes the log output to a file.
class CustomMultiOutput extends LogOutput {
  final File file;
  final bool overrideExisting;
  final Encoding encoding;
  late IOSink _sink;

  CustomMultiOutput({
    required this.file,
    this.overrideExisting = false,
    this.encoding = utf8,
  });

  @override
  Future<void> init() async {
    if(!file.existsSync()){
      RunningLogManager.instance.addLog('创建日志文件:${file.path}开始');
      file.createSync(recursive: true);
      _sink = file.openWrite(
        mode: overrideExisting ? FileMode.writeOnly : FileMode.writeOnlyAppend,
        encoding: encoding,
      );
      RunningLogManager.instance.addLog('创建日志文件:${file.path}结束');
    }else{
      RunningLogManager.instance.addLog('日志文件已存在:${file.path}');
    }
    _sink = file.openWrite(
      mode: overrideExisting ? FileMode.writeOnly : FileMode.writeOnlyAppend,
      encoding: encoding,
    );
  }

  @override
  void output(OutputEvent event) {
    // _sink.writeAll(event.lines, '\n');
    for (var line in event.lines) {
      var aTime = DateTime.now();
      var logWithTime = "$aTime : $line";
      print(logWithTime);
      _sink.writeln(logWithTime);
    }
  }

  @override
  Future<void> destroy() async {
    await _sink.flush();
    await _sink.close();
  }
}
